<?php

namespace App\DataProviders;

/**
 * Provides functionality for fetching airport data from a specific data source.
 */
readonly class AirportDataProvider implements AirportDataProviderInterface
{
    /**
     * @var string
     *
     * The URL from which airport data will be fetched.
     */
    private string $dataUrl;

    /**
     * Create a new AirportDataProvider instance.
     *
     * @param string $dataUrl The URL from which airport data will be fetched.
     */
    public function __construct(string $dataUrl)
    {
        $this->dataUrl = $dataUrl;
    }

    /**
     * Fetch the airport data from the defined URL and transform it into an array.
     *
     * @return array An array of airports, each represented as an associative array.
     */
    public function fetchAirportsData(): array
    {
        // Fetch the raw airport data from the URL.
        $airportsData = file_get_contents($this->dataUrl);

        // Decode the raw data into an associative array.
        $airports = json_decode($airportsData, true);

        // Ensure each airport has a 'code' attribute.
        foreach ($airports as $code => &$airport) {
            $airport['code'] = $code;
        }

        return $airports;
    }
}
